from fastapi import APIRouter, Depends
from sqlmodel import Session,select

from ...core.auth import get_current_user_with_permissions
from ...core.database import get_session
from ...crud.permission import get_menu_tree, get_user_menus_by_permission_codes
from ...models.permission import Menu, MenuPermission, Permission
from ...schemas.permission import MenuTree

router = APIRouter(prefix="/permissions", tags=["权限管理"])

@router.get("/menus", response_model=list[MenuTree])
async def get_user_menus(
        current_user_info: dict = Depends(get_current_user_with_permissions),
        session: Session = Depends(get_session)
):
    """获取当前用户的菜单权限"""
    user = current_user_info["user"]
    user_permissions = current_user_info["permissions"]

    # 获取菜单树
    menu_tree = get_menu_tree(session)

    # 如果是超级用户，返回所有菜单
    if user.is_superuser:
        return menu_tree

    # 过滤用户有权限的菜单
    # def filter_menu(menu: MenuTree):
    #     #
    #     user_menu_codes = session.exec(
    #         select(Menu.code)
    #         .join(MenuPermission)
    #         .join(Permission)
    #         .where(MenuPermission.menu_id == menu.id)
    #         .where(Permission.code.in_(user_permissions))
    #     ).all()
    user_menus = get_user_menus_by_permission_codes(session, user_permissions)

    def filter_menu(menu: MenuTree):
        if menu in user_menus:
            return menu

    filter_menus = [filter_menu(menu) for menu in menu_tree]
    return [menu for menu in filter_menus if menu is not None]


@router.get("/permissions/check")
async def check_permissions(
        permissions_code: str,
        current_user_info: dict = Depends(get_current_user_with_permissions)
):
    """检查用户是否有指定权限"""
    user = current_user_info["user"]
    user_permissions = current_user_info["permissions"]
    has_permission =  user.is_superuser or permissions_code in user_permissions
    return {"has_permission": has_permission}